package me.zhengjie.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.log4j.Log4j2;
import me.zhengjie.base.BaseBusiness;
import me.zhengjie.utils.SecurityUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.persistence.PostPersist;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.lang.reflect.Field;

/**
 * @author: YuJian
 * @date: 2021/6/22 13:17
 * @description:
 */
@Component
@Log4j2
public class DataBaseAuditListener {
    /**
     * 新增数据时，填充创建人和创建时间
     */
    @PrePersist
    public void prePersist(Object object)
            throws IllegalArgumentException, IllegalAccessException {
        // 如果填充字段被分装在一个父类中： Class<?> aClass = object.getClass().getSuperclass();
        Class<?> aClass = object.getClass();
        try {
            // 填充创建部门Id
            addDeptId(object, aClass, "lrbm");
            addDeptName(object, aClass, "lrbmmc");
            addUserId(object, aClass, "lrr");
            addUserId(object, aClass, "gxr");
        } catch (NoSuchFieldException e) {
            log.error("反射获取属性异常：", e);
        }


    }

    /**
     * 更新数据时，填充更新人和更新时间
     */
    @PreUpdate
    public void preUpdate(Object object)
            throws IllegalArgumentException, IllegalAccessException {
        Class<?> aClass = object.getClass();
        try {
            // 填充更新部门Id
            addDeptId(object, aClass, "gxbm");
            addDeptName(object, aClass, "gxbmmc");
            addUserId(object, aClass, "lrr");
            addUserId(object, aClass, "gxr");
        } catch (NoSuchFieldException e) {
            log.error("反射获取属性异常：", e);
        }
    }


    /**
     * 新增数据之后的操作
     */
    @PostPersist
    public void postPersist(Object object)
            throws IllegalArgumentException, IllegalAccessException {

    }

    /**
     * 更新数据之后的操作
     */
    @PostUpdate
    public void postUpdate(Object object)
            throws IllegalArgumentException, IllegalAccessException {
    }
    /**
     * 填充userId
     *
     * @param object:
     * @param aClass:
     * @param propertyName 属性名（对应实体类中的属性）
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    protected void addUserId(Object object, Class<?> aClass, String propertyName) throws NoSuchFieldException, IllegalAccessException {
        Class tClass = null;
        if(aClass.getSuperclass().getName().equals("me.zhengjie.base.BaseBusiness")){
            tClass = aClass.getSuperclass();
        }
        if(aClass.getSuperclass().getSuperclass().getName().equals("me.zhengjie.base.BaseBusiness")) {
            tClass = aClass.getSuperclass().getSuperclass();
        }
        Field userId = tClass.getDeclaredField(propertyName);
        userId.setAccessible(true);
        // 在此处使用当前UserId
        Long id = SecurityUtils.getCurrentUserId();
        userId.set(object, id);

    }

    /**
     * 填充部门id
     *
     * @param object:
     * @param aClass:
     * @param propertyName 属性名（对应实体类中的属性）
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    protected void addDeptId(Object object, Class<?> aClass, String propertyName) throws NoSuchFieldException, IllegalAccessException {
        Class tClass = null;
        if(aClass.getSuperclass().getName().equals("me.zhengjie.base.BaseBusiness")){
            tClass = aClass.getSuperclass();
        }
        if(aClass.getSuperclass().getSuperclass().getName().equals("me.zhengjie.base.BaseBusiness")) {
            tClass = aClass.getSuperclass().getSuperclass();
        }
        Field deptId = tClass.getDeclaredField(propertyName);
        deptId.setAccessible(true);
        // 在此处使用当前部门id或默认部门id
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        JSONObject deptObj = new JSONObject(new JSONObject(userDetails).get("dept"));
        System.out.println(deptObj);
        String id = deptObj.getStr("id");
        if (StrUtil.isNotEmpty(id)) {
            deptId.set(object, id);
        }
    }

    /**
     * 填充部门名称
     *
     * @param object:
     * @param aClass:
     * @param propertyName:
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private void addDeptName(Object object, Class<?> aClass, String propertyName) throws NoSuchFieldException, IllegalAccessException {
        Class tClass = null;
        if(aClass.getSuperclass().getName().equals("me.zhengjie.base.BaseBusiness")){
            tClass = aClass.getSuperclass();
        }
        if(aClass.getSuperclass().getSuperclass().getName().equals("me.zhengjie.base.BaseBusiness")) {
            tClass = aClass.getSuperclass().getSuperclass();
        }
        Field deptName = tClass.getDeclaredField(propertyName);
        deptName.setAccessible(true);
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        JSONObject deptObj = new JSONObject(new JSONObject(userDetails).get("dept"));
        String name = deptObj.getStr("name");
        if (StrUtil.isNotEmpty(name)) {
            deptName.set(object, name);
        }
    }
}
